/**
 * 恒丰银行
 * http://www.hfbank.com.cn
 * Copyright (c) 2017 All Rights Reserved.
 */
package com.chinamsp.configuration;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StopWatch;

import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.chinamsp.configuration.SwaggerSettingsProperties.ApiInfoProperties;

/**
 * 启动swagger进行API描述自动生成在线文档。
 * @author shifenghu
 * @version 1.0
 */
@EnableSwagger2
@AutoConfigureAfter(SwaggerSettingsProperties.class)
public class SwaggerConfiguration {

    private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);

    /**
     * 配置管理接口
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
	@Bean
    public Docket engineDocket(SwaggerSettingsProperties properties) {
        StopWatch watch = new StopWatch();
        watch.start();

        // 开始走起
        Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2)
            .groupName(properties.getGroupName()).apiInfo(apiInfo(properties.getApiInfo())).select()
            .paths(or(regex("^/(?!error).*$")))
            .build();

        watch.stop();
        log.debug("Started {} Swagger2 in {} ms", properties.getGroupName(), watch.getTotalTimeMillis());
        return swaggerSpringMvcPlugin;
    }
    
    @Bean
    public UiConfiguration uiConfig() {
    	return new UiConfiguration(
    			 null,
    		        "none",       
    		        "alpha",     
    		        "schema",     
    		        UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
    		        true,     
    		        true,     
    		        60000L 
    	);
    }

    /**
     * 初始化 api info
     * @param properties
     * @return
     */
    private ApiInfo apiInfo(ApiInfoProperties properties) {
    	if (properties == null){
    		properties = new ApiInfoProperties("chinamsp api", "");
    	}
        return new ApiInfo(properties.getTitle(), properties.getDescription(), properties.getVersion(),
            properties.getTermsOfServiceUrl(), 
            new Contact(properties.getContact().getName(), properties.getContact().getEmail(), properties.getContact().getUrl()),
            properties.getLicense(), properties.getLicenseUrl());
    }

}
